<template>
  <el-dialog
    :title="`${drawerProps.title}关键事件`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="1000px"
    :destroy-on-close="true"
  >
    <el-form
      ref="ruleFormRef"
      style="height: 70vh; overflow-y: auto"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-row>
        <el-col :span="23">
          <el-row>
            <form-item title="事件标题" prop="name" :title-span="3" :item-span="21">
              <el-input v-model="drawerProps.row!.name" clearable placeholder="请输入事件标题"></el-input>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="发生时间" prop="occ_time" :title-span="3" :item-span="5">
              <el-date-picker type="date" v-model="drawerProps.row!.occ_time" placeholder="请选择"></el-date-picker>
            </form-item>
            <form-item title="事件类型" prop="type" :title-span="3" :item-span="5">
              <cascader-select
                data-key="KEY_EVENT_TYPE"
                :request-api="() => apiService.findTree('param_exts', { csName: 'KEY_EVENT_TYPE' }, { sort: { sort: 1 } })"
                :config="{ label: 'name', value: '_id' }"
                v-model:item-value="drawerProps.row!.type"
              ></cascader-select>
            </form-item>
            <form-item title="发生客户" :title-span="3" :item-span="5">
              <cascader-select
                data-key="customer_classify"
                :request-api="() => apiService.findTree('param_exts', { csName: 'customer_classify' })"
                :config="{ label: 'name', value: '_id' }"
                v-model:item-value="drawerProps.row!.customer"
              ></cascader-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="负责人" prop="duty_userId" :title-span="3" :item-span="5">
              <user-select placeholder="请选择" v-model="drawerProps.row!.duty_userId"></user-select>
            </form-item>
            <form-item title="负责组织" prop="duty_orgId" :title-span="3" :item-span="5">
              <cascader-select
                data-key="orgs"
                :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
                :config="{ label: 'name', value: '_id', checkStrictly: true }"
                v-model:item-value="drawerProps.row!.duty_orgId"
              ></cascader-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="事件说明" prop="summary" :title-span="3" :item-span="21">
              <WangEditor height="300px" v-model:value="drawerProps.row.summary" :editor-config="editConfig" />
            </form-item>
          </el-row>
          <el-row>
            <form-item title="附件" :title-span="3" :item-span="21">
              <UploadFiles v-model:file-list="drawerProps.row.files" :drag="false" border-radius="50%"></UploadFiles>
            </form-item>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { KeyEvent } from "@/api/types/base";
import formItem from "@/components/application/form/form-item.vue";
import { BusinessType, BusinessOptType } from "@/enums/sysEnum";
import { useUserAction } from "@/hooks/useUserAction";
import { useUserStore } from "@/stores/modules/user";
import apiService from "@/api/services/apiService";
import CascaderSelect from "@/components/SelectFilter/cascader-select.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { IEditorConfig } from "@wangeditor/editor";
import UploadFiles from "@/components/Upload/Files.vue";
import userSelect from "@/components/SelectFilter/user-select.vue";

const { addUserAction } = useUserAction(BusinessType.SERVER);
const userStore = useUserStore();

const rules = reactive({
  name: [{ required: true, message: "请输入标题" }],
  occ_time: [{ required: true, message: "请选择发生事件" }],
  type: [{ required: true, message: "请选择事件类别" }],
  duty_orgId: [{ required: true, message: "请选择负责人" }],
  duty_userId: [{ required: true, message: "请选择负责组织" }],
  summary: [{ required: true, message: "请输入事件详情" }]
});

const editConfig: Partial<IEditorConfig> = {
  placeholder: "请输入事件详情……",
  MENU_CONF: {}
};

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<KeyEvent>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的环境
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）环境
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (drawerProps.value.title.indexOf("新增") != -1) {
        drawerProps.value.row.createDate = new Date();
        drawerProps.value.row.createUser = userStore.userInfo._id;
      }

      const data = await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      if (drawerProps.value.title.indexOf("新增") != -1) {
        addUserAction(data._id, BusinessOptType.ADD, data.name);
      } else {
        addUserAction(drawerProps.value.row._id, BusinessOptType.UPDATE, drawerProps.value.row.name);
      }
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
